package com.xsmous.open.avro;

import com.xsmous.open.codec.User;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;

import java.io.File;
import java.io.IOException;

/**
 * @author 雨一直夏灬
 * @slogan 年少无为、码上为生
 * @since 2020/5/30 9:36 上午
 */
public class AvroCodec {


    public static void main(String[] args) {

    }

    private static void decode() {
        // Deserialize Users from disk
        DatumReader<User> userDatumReader = new SpecificDatumReader<User>(User.class);
        DataFileReader<User> dataFileReader = null;
        try {
            dataFileReader = new DataFileReader<User>(new File("users.avro"), userDatumReader);
            User user = null;
            while (dataFileReader.hasNext()) {
                user = dataFileReader.next(user);
                System.out.println(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void encode() {
        // 1. 创建2个用户
        User user1 = new User();
        user1.setName("Alice");
        user1.setAge(12);
        user1.setGender("girl");
        user1.setHeight(138);

        User user2 = new User("Bob", 12, 187, "boy");

        User user3 = User.newBuilder().setName("Adam").setGender("boy").setAge(23).setHeight(175).build();


        // 2. 序列化并存储到磁盘文件
        DatumWriter<User> userDatumWriter = new SpecificDatumWriter<>(User.class);
        DataFileWriter<User> dataFileWriter = new DataFileWriter<>(userDatumWriter);
        try {
            dataFileWriter.create(user1.getSchema(), new File("users.avro"));
            dataFileWriter.append(user1);
            dataFileWriter.append(user2);
            dataFileWriter.append(user3);
            dataFileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
